<?php

namespace app\admin\controller;

use app\admin\controller\Base;
use \think\Request;
use think\facade\View;
use think\facade\Db;
use app\common\model\Infinite;
use app\common\model\ProductCate;
use app\common\model\Product as ProductModel;
use app\common\model\ProductNorms;
use app\common\model\ProductNormsValue;

class Product extends Base
{
    /**
     * 商品列表
     */
    public function index(Request $request)
    {
        $keyword = trim(input('get.keyword'));
        $status = trim(input('get.status'));
        $cate_id = $request->param("cate_id");
        $whe = array();
        if (!empty($keyword)) {
            $whe[] = ['title', 'like', '%' . $keyword . '%'];
        }

        if (!empty($status)) {
            $whe[] = ['status', '=', $status];
        } else {
            $whe[] = ['status', '<', '3'];
        }
        if (!empty($cate_id)) {
            $whe[] = ['cate_id', '=', $cate_id];
        }
        $field = "*";
        $order = "sort asc,id desc";
        $data = ProductModel::getList($whe, $field, $order, $this->page);
        foreach ($data['list'] as $k => &$v) {
            $v['cate_title'] = ProductCate::where(['id' => $v['cate_id']])->value("title");
        }
        $w = [];
        $w[] = ['pid', '=', '0'];
        $w[] = ['status', '=', '1'];
        $cate = ProductCate::getAllList($w, 'id,title');
        View::assign('cate', $cate);
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch("Product/index");
    }

    /**
     * 添加商品
     */
    public function add(Request $request)
    {
        if (!$request->isPost()) {
            $w = [];
            $w[] = ['pid', '=', '0'];
            $w[] = ['status', '=', '1'];
            $cate = ProductCate::getAllList($w, 'id,title');
            View::assign('cate', $cate);
            return View::fetch("Product/add");
        } else {
            $data = input('post.');
            $validate = validate('Product');
            try {
                $validate->scene('add')->check($data);
            } catch (\Exception  $e) {
                return $this->renderError($e->getError());
            }
            $num = explode(',', trim($data['imgurls'], ','));
            if (count($num) < 1 || count($num) > 5) {
                return $this->renderError("商品轮播图1-5张");
            }

            //添加商品关联的数据表
            $data_goods = []; //商品表
            $data_goods_norms = []; //商品规格属性表
            $data_goods_norms_value = []; //商品规格属性值表
            //商品表基础参数
            $data_goods['cate_id'] = $data['cate_id'];
            $data_goods['title'] = $data['title'];
            $data_goods['status'] = $data['status'];
            $data_goods['imgurl'] = $data['imgurl'];
            $data_goods['imgurls'] = trim($data['imgurls'], ',');
            $data_goods['norms_type'] = $data['norms_type'];
            $data_goods['addtime'] = time();
            $data_goods['content'] = $data['content'];
            $data_goods['sort'] = $data['sort'];
            $data_goods['yunfei'] = $data['yunfei'];
            $data_goods['is_tui'] = $data['is_tui'];

            //规格属性：1单规格，2多规格
            $norms_type = $data['norms_type'];
            if ($norms_type == 1) {
                //必须输入价格
                if (!preg_match('/^[0-9]+\d*(.\d{1,2})?$/', $data['attr_price'])) {
                    return $this->renderError('请输入商品售价');
                }
                if (!preg_match('/^[0-9]+\d*(.\d{1,2})?$/', $data['attr_old_price'])) {
                    // return $this->renderError('请输入商品原价');
                }
                if (empty($data['attr_imgurl'])) {
                    return $this->renderError('请上传规格图片');
                }
                if (!empty($data['attr_stock']) && $data['attr_stock'] < 0) {
                    return $this->renderError('商品库存不合法');
                }

                //商品表参数
                $data_goods['price'] = $data['attr_price'];
                $data_goods['old_price'] = $data['attr_old_price'];
                $data_goods['stock'] = $data['attr_stock'];
                $data_goods['imgurl'] = $data['attr_imgurl'];
                //商品规格属性表参数
                $data_goods_norms['norms_name'] = '规格';
                $data_goods_norms['norms_values'] = '默认';
                //商品规格属性值表参数
                $data_goods_norms_value['sku'] = '默认';
                $data_goods_norms_value['stock'] = $data['attr_stock'];
                $data_goods_norms_value['price'] = $data['attr_price'];
                $data_goods_norms_value['old_price'] = $data['attr_old_price'];
                $data_goods_norms_value['imgurl'] = $data['attr_imgurl'];
                if (empty($data['attr_imgurl'])) {
                    $data_goods_norms_value['imgurl'] = $data['imgurl'];
                } else {
                    $data_goods_norms_value['imgurl'] = $data['attr_imgurl'];
                }
                ProductModel::startTrans();
                try {
                    $result1 = ProductModel::insertGetId($data_goods);
                    $data_goods_norms['product_id'] = $result1;
                    $result2 = ProductNorms::insert($data_goods_norms);
                    $data_goods_norms_value['product_id'] = $result1;
                    $result3 = ProductNormsValue::insert($data_goods_norms_value);
                    if ($result1 && $result2 && $result3) {
                        ProductModel::commit();
                        return $this->renderSuccess('添加成功');
                    } else {
                        ProductModel::rollback();
                        return $this->renderError('添加失败');
                    }
                } catch (\Exception $e) {
                    ProductModel::rollback();
                    return $this->renderError($e->getMessage());
                }
            } else {
                $norms = $data['lv1'];
                $norms_value = $data['lv2'];
                if (empty($norms)) {
                    return $this->renderError('规格名称不能空');
                }
                if (empty($norms_value)) {
                    return $this->renderError('规格属性不能空');
                }
                foreach ($norms as $k => $v) {
                    if (empty($v)) {
                        return $this->renderError('请将规格名称输入完整');
                    }
                    if (empty($norms_value[$k])) {
                        return $this->renderError('请删除没有属性的规格：' . $v);
                    }
                    foreach ($norms_value[$k] as $key => $val) {
                        if (empty($val)) {
                            return $this->renderError('请将“' . $v . '”规格属性输入完整');
                        }
                    }
                    $data_goods_norms[$k]['norms_name'] = $v;
                    $data_goods_norms[$k]['norms_values'] = implode($norms_value[$k], ',');
                }

                $data_goods_norms_value = array();
                $attr_value = $data['attr_value'];
                if (empty($attr_value)) {
                    return $this->renderError('请输入规格项');
                }
                $stock = 0;
                foreach ($attr_value as $k => $v) {
                    $sku = strtr($v['sku'], '_', ',');
                    $data_goods_norms_value[$k]['sku'] = $sku; //规格
                    $data_goods_norms_value[$k]['stock'] = $v['stock']; //库存
                    $data_goods_norms_value[$k]['sales'] = 0; //销量
                    $data_goods_norms_value[$k]['price'] = $v['price']; //现价
                    $data_goods_norms_value[$k]['old_price'] = $v['old_price']; //原价
                    $data_goods_norms_value[$k]['imgurl'] = $v['imgurl']; //原价
                    $stock += $v['stock'];
                }
                //获取规格最小价格
                $attr_value_price = array_column($attr_value, 'price');
                $data_goods['price'] = min($attr_value_price);
                $data_goods['stock'] = $stock;

                ProductModel::startTrans();
                try {
                    $result1 = ProductModel::insertGetId($data_goods);
                    if ($result1) {
                        foreach ($data_goods_norms as $k => $v) {
                            $data_goods_norms[$k]['product_id'] = $result1;
                        }
                        foreach ($data_goods_norms_value as $k => $v) {
                            $data_goods_norms_value[$k]['product_id'] = $result1;
                            $data_goods_norms_value[$k]['imgurl'] = $v['imgurl'];
                        }
                        $result2 = ProductNorms::insertAll($data_goods_norms);
                        $result3 = ProductNormsValue::insertAll($data_goods_norms_value);
                    } else {
                        ProductModel::rollback();
                        return $this->renderError('商品添加失败');
                    }
                    if ($result1 && $result2 && $result3) {
                        ProductModel::commit();
                        return $this->renderSuccess('添加成功');
                    } else {
                        ProductModel::rollback();
                        return $this->renderError('添加失败');
                    }
                } catch (\Exception $e) {
                    ProductModel::rollback();
                    return $this->renderError($e->getMessage());
                }
            }
        }
    }

    /**
     * 编辑商品
     */
    public function edit(Request $request)
    {
        if (!$request->isPost()) {
            $id = $request->param('id');
            //商品详情
            $data = ProductModel::getInfo(['id' => $id], '*');
            if (empty($data)) {
                return $this->error("参数错误");
            }
            View::assign('data', $data);
            $imgurls = explode(',', $data['imgurls']);
            View::assign('imgurls', $imgurls);
            $product_norms = ProductNorms::getAllList(['product_id' => $id], 'id,norms_name,norms_values');
            foreach ($product_norms as $k => $v) {
                $product_norms[$k]['norms_values'] = explode(',', $v['norms_values']);
            }
            $product_norms_value = ProductNormsValue::getAllList(['product_id' => $id], 'id,sku,stock,price,old_price,imgurl');
            //一级分类
            $w = [];
            $w[] = ['pid', '=', '0'];
            $w[] = ['status', '=', '1'];
            $cate = ProductCate::getAllList($w, 'id,title');
            View::assign('cate', $cate);
            View::assign('product_norms', $product_norms);
            View::assign('product_norms_value', $product_norms_value);
            return View::fetch("Product/edit");
        } else {
            $id = $request->param('id');
            $data = input('post.');
            $validate = validate('Product');
            try {
                $validate->scene('edit')->check($data);
            } catch (\Exception  $e) {
                return $this->renderError($e->getError());
            }

            $num = explode(',', trim($data['imgurls'], ','));
            if (count($num) < 1 || count($num) > 5) {
                // return $this->renderError("商品轮播图1-5张");
            }

            $product = ProductModel::getInfo(['id' => $id], '*');
            //添加商品关联的数据表
            $data_goods = []; //商品表
            $data_goods_norms = []; //商品规格属性表
            $data_goods_norms_value = []; //商品规格属性值表
            //商品表基础参数
            $data_goods['cate_id'] = $data['cate_id'];
            $data_goods['title'] = $data['title'];
            $data_goods['status'] = $data['status'];
            $data_goods['imgurl'] = $data['imgurl'];
            $data_goods['imgurls'] = trim($data['imgurls'], ',');
            $data_goods['norms_type'] = $data['norms_type'];
            $data_goods['addtime'] = time();
            $data_goods['content'] = $data['content'];
            $data_goods['sort'] = $data['sort'];
            $data_goods['yunfei'] = $data['yunfei'];
            $data_goods['is_tui'] = $data['is_tui'];

            //规格属性：1单规格，2多规格
            $norms_type = $data['norms_type'];
            if ($norms_type == 1) {
                //必须输入价格
                if (!preg_match('/^[0-9]+\d*(.\d{1,2})?$/', $data['attr_price'])) {
                    return $this->renderError('请输入商品售价');
                }
                if (!preg_match('/^[0-9]+\d*(.\d{1,2})?$/', $data['attr_old_price'])) {
                    // return $this->renderError('请输入商品原价');
                }
                if (!empty($data['attr_stock']) && $data['attr_stock'] < 0) {
                    return $this->renderError('商品库存不合法');
                }
                //商品表参数
                $data_goods['price'] = $data['attr_price'];
                $data_goods['old_price'] = $data['attr_old_price'];
                $data_goods['stock'] = $data['attr_stock'];
                $data_goods['imgurl'] = $data['attr_imgurl'];
                //商品规格属性表参数
                $data_goods_norms['norms_name'] = '规格';
                $data_goods_norms['norms_values'] = '默认';
                //商品规格属性值表参数
                $data_goods_norms_value['sku'] = '默认';
                $data_goods_norms_value['stock'] = $data['attr_stock'];
                $data_goods_norms_value['price'] = $data['attr_price'];
                $data_goods_norms_value['old_price'] = $data['attr_old_price'];
                $data_goods_norms_value['imgurl'] = $data['attr_imgurl'];
                if (empty($data['attr_imgurl'])) {
                    $data_goods_norms_value['imgurl'] = $data['imgurl'];
                } else {
                    $data_goods_norms_value['imgurl'] = $data['attr_imgurl'];
                }

                ProductModel::startTrans();
                $result1 = true;
                $result2 = true;
                $result3 = true;
                $result4 = true;
                $result5 = true;
                try {
                    //更新商品信息
                    $result1 = ProductModel::where(['id' => $id])->update($data_goods);
                    //判断原来的商品是单规格还是多规格，单规格：修改规格信息；多规格：删除多规格信息，新增单规格信息
                    if ($product['norms_type'] == 1) { //单规格
                        //删除多规格
                        $result4 = ProductNorms::where('product_id', $id)->delete();
                        $result5 = ProductNormsValue::where('product_id', $id)->delete();
                        //新增单规格信息
                        $data_goods_norms['product_id'] = $id;
                        $data_goods_norms_value['product_id'] = $id;
                        $result2 = ProductNorms::insert($data_goods_norms);
                        $result3 = ProductNormsValue::insert($data_goods_norms_value);
                    } else { //多规格
                        //删除多规格
                        $result4 = ProductNorms::where('product_id', $id)->delete();
                        $result5 = ProductNormsValue::where('product_id', $id)->delete();
                        //新增单规格信息
                        $data_goods_norms['product_id'] = $id;
                        $data_goods_norms_value['product_id'] = $id;
                        $result2 = ProductNorms::insert($data_goods_norms);
                        $result3 = ProductNormsValue::insert($data_goods_norms_value);
                    }
                    if ($result1 && $result2 && $result3 && $result4 && $result5) {
                        ProductModel::commit();
                        return $this->renderSuccess('编辑成功');
                    } else {
                        ProductModel::rollback();
                        return $this->renderError('编辑失败' . $result1 . $result2 . $result3 . $result4 . $result5);
                    }
                } catch (\Exception $e) {
                    ProductModel::rollback();
                    return $this->renderError($e->getMessage());
                }
            } else {
                $norms = $data['lv1'];
                $norms_value = $data['lv2'];
                if (empty($norms)) {
                    return $this->renderError('规格名称不能空');
                }
                if (empty($norms_value)) {
                    return $this->renderError('规格属性不能空');
                }
                foreach ($norms as $k => $v) {
                    if (empty($v)) {
                        return $this->renderError('请将规格名称输入完整');
                    }
                    if (empty($norms_value[$k])) {
                        return $this->renderError('请删除没有属性的规格：' . $v);
                    }
                    foreach ($norms_value[$k] as $key => $val) {
                        if (empty($val)) {
                            return $this->renderError('请将“' . $v . '”规格属性输入完整');
                        }
                    }
                    $data_goods_norms[$k]['norms_name'] = $v;
                    $data_goods_norms[$k]['norms_values'] = implode($norms_value[$k], ',');
                }

                $data_goods_norms_value = array();
                $attr_value = $data['attr_value'];
                if (empty($attr_value)) {
                    return show(1, '请输入规格项');
                }
                $stock = 0;
                foreach ($attr_value as $k => $v) {
                    $sku = strtr($v['sku'], '_', ',');
                    $data_goods_norms_value[$k]['sku'] = $sku; //规格
                    $data_goods_norms_value[$k]['stock'] = $v['stock']; //库存
                    $data_goods_norms_value[$k]['sales'] = 0; //销量
                    $data_goods_norms_value[$k]['price'] = $v['price']; //现价
                    $data_goods_norms_value[$k]['old_price'] = $v['old_price']; //原价
                    $data_goods_norms_value[$k]['imgurl'] = $v['imgurl']; //规格图片
                    $stock += $v['stock'];
                }
                //获取规格最小价格
                $attr_value_price = array_column($attr_value, 'price');
                $data_goods['price'] = min($attr_value_price);
                $data_goods['stock'] = $stock;

                ProductModel::startTrans();
                $result1 = true;
                $result2 = true;
                $result3 = true;
                $result4 = true;
                $result5 = true;
                try {
                    //更新商品信息
                    $result1 = ProductModel::where(['id' => $id])->update($data_goods);
                    if ($result1) {
                        //判断原来的商品是单规格还是多规格，单规格：删除单规格信息，新增多规格；多规格：获取销量，删除多规格，新增多规格
                        if ($product['norms_type'] == 1) { //单规格
                            foreach ($data_goods_norms as $k => $v) {
                                $data_goods_norms[$k]['product_id'] = $id;
                            }
                            foreach ($data_goods_norms_value as $k => $v) {
                                $data_goods_norms_value[$k]['product_id'] = $id;
                                $data_goods_norms_value[$k]['imgurl'] = $v['imgurl'];
                            }
                            //删除单规格
                            $result4 = ProductNorms::where('product_id', $id)->delete();
                            $result5 = ProductNormsValue::where('product_id', $id)->delete();

                            $result2 = ProductNorms::insertAll($data_goods_norms);
                            $result3 = ProductNormsValue::insertAll($data_goods_norms_value);
                        } else { //多规格
                            foreach ($data_goods_norms as $k => $v) {
                                $data_goods_norms[$k]['product_id'] = $id;
                            }

                            foreach ($data_goods_norms_value as $k => $v) {
                                $sales = ProductNormsValue::where(['product_id' => $id, 'sku' => $v['sku']])->value('sales');
                                if ($sales) {
                                    $data_goods_norms_value[$k]['sales'] = $sales;
                                }
                                $data_goods_norms_value[$k]['product_id'] = $id;
                                $data_goods_norms_value[$k]['imgurl'] = $v['imgurl'];
                            }
                            //删除规格
                            $result4 = ProductNorms::where('product_id', $id)->delete();
                            $result5 = ProductNormsValue::where('product_id', $id)->delete();

                            $result2 = ProductNorms::insertAll($data_goods_norms);
                            $result3 = ProductNormsValue::insertAll($data_goods_norms_value);
                        }
                    } else {
                        ProductModel::rollback();
                        return $this->renderError('商品编辑失败');
                    }

                    if ($result1 && $result2 && $result3) {
                        ProductModel::commit();
                        return $this->renderSuccess('编辑成功');
                    } else {
                        ProductModel::rollback();
                        return $this->renderError('编辑失败');
                    }
                } catch (\Exception $e) {
                    ProductModel::rollback();
                    return $this->renderError($e->getMessage());
                }
            }
        }
    }


    //生成sku
    public function get_format_attr(Request $request)
    {
        $type = $request->param('type'); //类型：0编辑时直接获取,1刷新生成新规格
        $product_id = $request->param('product_id'); //商品id
        $lv1_json = $request->param('lv1_json'); //规格
        $lv2_json = $request->param('lv2_json'); //规格属性值
        $lv1 = json_decode($lv1_json, true);
        $lv2 = json_decode($lv2_json, true);
        if (empty($lv1) || empty($lv2)) {
            return $this->renderError('请添加规格和属性');
        }
        foreach ($lv2 as $k => $v) {
            if (empty($v)) {
                return $this->renderError('请添加完整的规格和属性');
            }
        }
        //dump($lv1);
        //dump($lv2);die;
        $attr = [];
        foreach ($lv1 as $k => $v) {
            if (empty($v)) {
                return $this->renderError('请将规格名称填写完整');
            }
            if (empty($lv2[$k])) {
                return $this->renderError('请将' . $v . '规格属性填写完整');
            }
            foreach ($lv2[$k] as $kk => $vv) {
                if (empty($vv)) {
                    return $this->renderError('请将' . $v . '规格属性填写完整！');
                }
            }
            $attr[$k]['value'] = $v;
            $attr[$k]['detail'] = $lv2[$k];
        }
        //dump($attr);
        $value = attr_format($attr)[1];
        // dd($value);
        $valueNew = [];
        $count = 0;
        foreach ($value as $key => $item) {
            $detail = $item['detail'];
            sort($item['detail'], SORT_STRING);
            $sku = implode(',', $item['detail']);
            $types = 1;
            if ($product_id) {
                $sukValue = ProductNormsValue::where('product_id', $product_id)->where('sku', $sku)->column('stock,price,old_price,imgurl', 'sku');
                // var_dump($sukValue);
                if (!count($sukValue)) {
                    //if ($type == 0) $types = 0; //编辑商品时，将没有规格的数据不生成默认值
                    $sukValue[$sku]['stock'] = 0;
                    $sukValue[$sku]['price'] = 0;
                    $sukValue[$sku]['old_price'] = 0;
                    $sukValue[$sku]['imgurl'] = '';
                }
            } else {
                $sukValue[$sku]['stock'] = 0;
                $sukValue[$sku]['price'] = 0;
                $sukValue[$sku]['old_price'] = 0;
                $sukValue[$sku]['imgurl'] = '';
            }
            if ($types) { //编辑商品时，将没有规格的数据不生成默认值
                foreach (array_keys($detail) as $k => $title) {
                    $header[$k]['title'] = $title;
                    $header[$k]['width'] = 50;
                }
                foreach (array_values($detail) as $k => $v) {
                    $valueNew[$count]['value' . ($k)] = $v;
                    $header[$k]['key'] = 'value' . ($k);
                }
                $valueNew[$count]['detail'] = implode('_', $item['detail']);
                $valueNew[$count]['stock'] = $sukValue[$sku]['stock'] ? intval($sukValue[$sku]['stock']) : 0;
                $valueNew[$count]['price'] = $sukValue[$sku]['price'] ? floatval($sukValue[$sku]['price']) : 0;
                $valueNew[$count]['old_price'] = isset($sukValue[$sku]['old_price']) ? floatval($sukValue[$sku]['old_price']) : 0;
                $valueNew[$count]['imgurl'] = isset($sukValue[$sku]['imgurl']) ? $sukValue[$sku]['imgurl'] : '';
                $valueNew[$count]['imgurls'] = isset($sukValue[$sku]['imgurl']) ? imageUrl($sukValue[$sku]['imgurl']) : '';
                $count++;
            }
        }
        // dd($valueNew);
        $header[] = ['title' => '图片', 'width' => 20];
        $header[] = ['title' => '现价', 'width' => 20];
        // $header[] = ['title'=>'原价','width'=>20];
        $header[] = ['title' => '库存', 'width' => 20];
        //dump($header);
        // dump($valueNew);die;
        $return['attr'] = $attr;
        $return['value'] = $valueNew;
        $return['header'] = $header;
        return $this->renderSuccess('请求成功', $return);
    }

    /**
     * 删除商品
     */
    public function del(Request $request)
    {
        $id = $request->post('id/d');
        $status = $request->post('stu/d');
        if (!in_array($status, array(1, 2, 3))) {
            return $this->renderError("数据错误");
        }
        $data = ProductModel::where(['id' => $id])->field('id')->find();
        if (!$data) {
            return $this->renderError("数据不存在");
        }
        $result = ProductModel::where(['id' => $id])->update(["status" => $status]);
        if ($result) {
            return $this->renderSuccess("操作成功");
        } else {
            return $this->renderError("网络繁忙，请稍后");
        }
    }

    /**
     *采集商品
     */
    public function caiji(Request $request)
    {
        $w = [];
        $w[] = ['pid', '=', '0'];
        $w[] = ['status', '=', '1'];
        $cate = ProductCate::getAllList($w, 'id,title');
        View::assign('cate', $cate);
        return View::fetch("Product/caiji");
    }

    /**
     *采集商品保存
     */
    public function caiji_save()
    {

        $data = request()->post();

        if (empty($data['cate_id1'])) {
            return $this->renderError('请选择一级分类');
        }
        if (empty($data['apikey'])) {
            return $this->renderError('请输入99APIKEY');
        }
        if (empty($data['url'])) {
            return $this->renderError('请输入商品ID或商品链接');
        }
        session('apikey_id', $data['apikey']);


        Db::startTrans();
        $res = [];
        // foreach ($url_arr as $k => $v){
        $url = $data['url'];
        if (is_numeric($url)) {
            $jdid = $url;
        } else {
            $urlArr = explode('item.jd.com/', $url);
            // dd($urlArr);
            $jdid = explode('.html', $urlArr[1])[0];
        }
        #采集
        $caiji_info = $this->curl_get('https://api03.6bqb.com/jd/detail?apikey=' . trim($data['apikey']) . '&itemid=' . $jdid);

        if (!$caiji_info) {
            return $this->renderError('采集失败');
        }
        // dd($caiji_info);
        $product = $caiji_info['data']['item'];
        $title = $product['name'];#商品名称
        $images = $product['images'];#详情图
        $imgurl = $images[0];#主图
        $content = '';
        $descImgs = $product['descImgs'];#内容
        $price = $product['price'];
        $old_price = $product['originalPrice'];
        foreach ($descImgs as $k => $v) {
            $content .= '<p><img src="' . $v . '" width="100%"/></p>';
        }
        #新增商品
        $dd = $product_id = Db::name('product')->insertGetId([
            'title' => $title,
            'imgurl' => $imgurl,
            'imgurls' => implode(',', $images),
            'price' => $price,
            'old_price' => $old_price,
            'cate_id' => $data['cate_id1'],
            'sort' => $data['sort'],
            'sales' => 0,
            'addtime' => time(),
            'status' => 2,
            'norms_type' => 2,
            'content' => $content,
            'yunfei' => $data['yunfei'],
            'is_caiji' => 1,
        ]);


        $saleProp = $product['saleProp'];#规格大项
        $skuProps = $product['skuProps'];#规格小项
        $product_norms = [];
        foreach ($skuProps as $k => $v) {
            if (!empty($v[0])) {
                $product_norms[] = [
                    'product_id' => $product_id,
                    'norms_name' => $saleProp[$k],
                    'norms_values' => implode(',', $v)
                ];
            }

        }

        // dd($product);
        $sku = $product['sku'];#规格组合项
        $m_stock = 999;#默认库存
        $stock = 0;
        $items = [];
        // dd($sku);
        foreach ($sku as $k => $v) {
            if (!empty($v)) {
                $spec_name = [];
                for ($i = 1; $i <= count($product_norms); $i++) {
                    $spec_name[] = $v[$i];
                }
                $items[] = [
                    'spec_name' => implode(',', $spec_name),
                    'price' => isset($v['price']) ? $v['price'] : 0,
                    'old_price' => 0,
                    'stock' => $m_stock,
                    // 'imgurl'=>'https://img30.360buyimg.com/popWaterMark/'.$v['imagePath'],
                    'imgurl' => $imgurl,
                ];
                $stock += $m_stock;
            }

        }
        // dd($items);
        $product_norms_value = [];
        $product_norms_value_res = $this->getPermutation($skuProps);

        foreach ($product_norms_value_res as $k => $v) {
            foreach ($items as $kk => $vv) {
                if (trim($vv['spec_name']) == trim($v)) {
                    $info = $vv;

                    $my_v = explode(',', $v);
                    sort($my_v, SORT_STRING);
                    $v = implode(',', $my_v);

                    $product_norms_value[] = [
                        'product_id' => $product_id,
                        'sku' => $v,
                        'stock' => $info['stock'],
                        'sales' => 0,
                        'price' => $info['price'],
                        'old_price' => $info['old_price'],
                        'imgurl' => $info['imgurl'],
                    ];
                    // break;
                }
            }
        }
        // dd($product_norms_value);
        #新增商品
        $ss = Db::name('product_norms')->insertAll($product_norms);
        $mm = Db::name('product_norms_value')->insertAll($product_norms_value);
        $pp = Db::name('product')->where(['id' => $product_id])->update(['stock' => $stock,]);

        if ($dd && $ss && $mm && $pp) {
            Db::commit();
            return $this->renderSuccess("采集成功");
        } else {
            Db::rollback();
            return $this->renderError("采集失败");
        }
    }


    #多规格的排列组合
    public function getPermutation($res_arr = [])
    {

        $res = [];
        foreach ($res_arr as $k => $v) {
            if (!empty($v[0])) {
                $res[] = $v;
            }
        }
        $data = [];
        if (empty($res)) {
            return $res;
        }
        if (count($res) <= 1) {
            return $res[0];
        } else {

            $res = $this->specArrCombination($res);
            foreach ($res as $k => $v) {
                $data[$k] = implode(',', $v);
            }
        }
        return $data;
    }


    public function specArrCombination($arr, $i = 0, $tmp = [])
    {
        $g_a = [];
        if (count($arr) - 1 <= $i) {
            $ar = [];
            foreach ($arr[$i] as $key => $val) {
                $tmp_sukarr = [];
                if ($i == 0) {
                    $tmp_sukarr[] = $val;
                    $ar[] = $tmp_sukarr;
                } else {
                    $tmp_sukarr = $tmp;
                    $tmp_sukarr[] = $val;
                    $ar[] = $tmp_sukarr;
                }
            }
            return $ar;
        } else {

            foreach ($arr[$i] as $key => $val) {
                $tmp_sukarr = [];

                if (count($tmp) <= 0) {
                    $tmp_sukarr[] = $val;
                } else {
                    $tmp_sukarr = $tmp;
                    $tmp_sukarr[] = $val;
                }

                $tmpNode = $tmp_sukarr;
                $g_a = array_merge($g_a, $this->specArrCombination($arr, $i + 1, $tmpNode));

            }
        }
        return $g_a;
    }

    public function curl_get($url = '')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_ENCODING, "gzip");
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        $response = curl_exec($curl);

        $err = curl_error($curl);
        curl_close($curl);
        if ($err) {
            return $this->renderError($err);
        } else {
            return json_decode($response, true);
        }
    }
}